import { useTableState } from "@/state/hopetoTable";
import { Input } from "@arco-design/web-react";
import { memo, useEffect, useState } from "react";
import { IColumn } from ".";
import { TableCell } from "./TableCell";

interface IProps {
  /** 表格项原始渲染内容 */
  children: React.ReactElement;
  /** 表格列配置 */
  column: IColumn;
  /** 数据所在行 */
  dataIndex: number;
  /** 行数据 */
  rowData: any;
  /** 完成编辑 */
  onFinishEdit: (val: any) => void;
  /** 编辑值变化 */
  onEditChange: (val: any) => void;
  /** 表格ID */
  tableId: string;
  /** 可编辑列 */
  editableCols: string[];
}

/** 可编辑表格项 */
const EditableCell = memo((props: IProps) => {
  const {
    children,
    column,
  } = props;

  if (!column.editable) return children;
  return <CellWithEditingState {...props} />;
});

/** 表格项携带编辑的数据(hopetoTableState变化，只重新渲染可编辑单元格) */
const CellWithEditingState = memo((props: IProps) => {
  const {
    children,
    column,
    dataIndex,
    rowData,
    onFinishEdit,
    onEditChange,
    tableId,
    editableCols = [],
  } = props;
  const {
    data: tableState,
    setFocusCell,
    setCellIsEditing
} = useTableState(tableId);
  const { focusCell, cellIsEditing } = tableState;
  const focusCellKey = editableCols[focusCell[1]];

  const focused = tableId === tableState.tableId && focusCell?.[0] === dataIndex && focusCellKey === column.key;
  const [value, setValue] = useState(rowData[column.dataIndex!]);

  useEffect(() => {
    if (focused) setValue(rowData[column.dataIndex!]);
  }, [focused]);

  if (focused && cellIsEditing) {
    return (
      <div style={{ width: "100%" }}>
        <Input
          style={{ width: "100%" }}
          height={32}
          autoFocus
          onPressEnter={(evt) => {
            setCellIsEditing(false);
            onFinishEdit(value);
            evt.stopPropagation();
          }}
          onFocus={(evt) => {
            console.log("onFocus");
            evt.target.select();
          }}
          value={value == 0 ? '' : value}
          onChange={(val) => {
            onEditChange(val);
            setValue(val);
          }}
        />
      </div>
    );
  }

  return (
    <TableCell
      style={{
        cursor: "cell",
        border: `1px solid ${focused ? "#94BFFF" : "transparent"}`,
        padding: 0
      }}
      origin={
        <div
          // onDoubleClick={(evt) => {
          //   setFocusCell([
          //     dataIndex,
          //     editableCols.indexOf(column.key || (column.dataIndex! as any)),
          //   ]);
          //   setCellIsEditing(true);
          //   evt.stopPropagation();
          // }}
          onClick={(evt) => {
            setFocusCell([
              dataIndex,
              editableCols.indexOf(column.key || (column.dataIndex! as any)),
            ]);
            setCellIsEditing(true);
            evt.stopPropagation();
          }}
        >
          {children}
        </div>
      }
    />
  );
});

export { EditableCell };

